package com.xl.xlserver.mode.cliect;

import com.alibaba.fastjson.JSONObject;
import com.xl.xlserver.GameUtilEntity.Play;
import com.xl.xlserver.GameUtilEntity.ScokectMessger;
import com.xl.xlserver.constant.CliectXYModeCode;
import com.xl.xlserver.gameServer.LobbyManager;
import com.xl.xlserver.mode.login.InitMode;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.lang3.StringUtils;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

public class ClientXYMode {

    public  void  ClientXYMode(ScokectMessger manger, ChannelHandlerContext ctx){
        if (manger.getModeCode() == CliectXYModeCode.REAL_USER){
            //实时推送用户地址数据
            String data = manger.getData();
            if (StringUtils.isEmpty(data)){
                return;
            }
            InitMode.getInitMode().addPlay(ctx,manger);
            System.out.println("添加进入玩家");
            getallPalys(data,ctx);

        }else  if (manger.getModeCode() == CliectXYModeCode.identity || manger.getModeCode() == CliectXYModeCode.Attack){
            //攻击或移动
            moveAndAttack(manger,ctx);
        }
    }


    public void getallPalys(String code, ChannelHandlerContext ctx) {

        Play play = new Play("1290", "张三", 20, 40, "2", 1);
        Play play2 = new Play("1870", "李四", 45, 67, "2", 1);


        //实时推送用户地址数据
        if (StringUtils.isEmpty(code)) {
            return;
        } else {

            for (Map.Entry<String, Play> entry : LobbyManager.playerManager.entrySet()) {
                Map<String, Play> result = new HashMap<>();
                if (code.equals(entry.getValue().getMapCode())) {
                    result.put(entry.getKey(), entry.getValue());
                }
            }


            String data = JSONObject.toJSONString(LobbyManager.playerManager);
            System.out.println("发送地址:"+data);
            ByteBuf resp = Unpooled.copiedBuffer(data.getBytes());
            ctx.write(resp);
            ctx.flush();
        }
    }

    /**
     * 移动或攻击
     */
    public  void  moveAndAttack(ScokectMessger manger, ChannelHandlerContext ctx){
        String scennd = ctx.channel().id().toString();
        InetSocketAddress ipSocket = (InetSocketAddress)ctx.channel().remoteAddress();
        String clientIp = ipSocket.getAddress().getHostAddress();
        int post = ipSocket.getPort();
        Play play =  JSONObject.parseObject(manger.getData(),Play.class);
        LobbyManager.getInstance().replacePlayer(clientIp+":"+post,ctx,play);

        InitMode.getInitMode().SendaLLMessage(ctx,play.getMapCode(),manger.getData());

    }
}
